using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Scarfy.Core.Data;
using Scarfy.Core.Business;

/**
 * Edit your Web.config and add in
      <add verb="*" path="*.php" validate="false" type="Scarfy.SocialNetworking.MoodlePHPHandler"/>
 * inside <httpHandlers>
 * */

namespace Scarfy.SocialNetworking
{
    public class MoodlePHPHandler : IHttpHandler, IRequiresSessionState
    {
        bool IHttpHandler.IsReusable
        {
            get { return true; }
        }

        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            string path = context.Request.AppRelativeCurrentExecutionFilePath;
            string method = context.Request.HttpMethod;

            MoodleRequest.GenerateCertificate("http://www.scarfy.co.nz");

            MoodleAuth moodle = new MoodleAuth();

            if (path == "~/mnet/publickey.php" && method == "GET")
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write(moodle.PublicKey);
            }
            else if ((path == "~/mnet/xmlrpc/server.php" || //Moodle way of doing it
                     path == "~/api/xmlrpc/server.php") //Mahara's way of doing it
                     && method == "POST")
            {
                //This is called when a remote Moodle or Mahara wants to communicate with us
                context.Response.ContentType = "text/xml";
                //all requests are supposed to be encrypted and signed, except for "system/keyswap"
				StreamReader input = new StreamReader(context.Request.InputStream);
				string data = input.ReadToEnd();
				bool isEncrypted = false;
				bool isSigned = false;
				if (data.Substring(0, 100).Contains("<encryptedMessage>"))
				{
					//decrypt the encrypted message here
					data = MnetDecryptMessage(data);
					isEncrypted = true;
				}
				if (data.Substring(0, 100).Contains("<signedMessage>"))
				{
					//unsign the signed message here
					data = MnetUnsignMessage(data, RemoteCertificate);
					isSigned = true;
				}

				XmlRpcRequest req = (XmlRpcRequest)new XmlRpcRequestDeserializer().Deserialize(data);
				if (isEncrypted && isSigned || req.MethodName == "system/keyswap")
				{
					//Request is ok, process it
				} else {
					//Request is bad
					context.Response.StatusCode = 304;
				}
				XmlRpcResponse resp = new XmlRpcResponse();
            } else if (path == "~/auth/mnet/jump.php" && method == "GET")
            {
                //this is called when a Moodle site wants to use Scarfy for authentication
                // eg http://millie.id.co.nz/moodle/auth/mnet/jump.php?hostwwwroot=http://www.scarfy.co.nz&wantsurl=&hostid=4
                //hostwwwroot - the host to go back to (only in v1.9 of Moodle)
                //wantsurl - the url on that host to to back to (after the land page)
                //hostid - the id number of our host on remote server (only in v1.8 or earlier)
                String RemoteServer = context.Request.Params["hostwwwroot"];
                String URL = context.Request.Params["wantsurl"];

                //Need to generate a token, if there's a logged in user
                UserAccount acct = UserAccount.GetCurrentUserAccount();
                if (acct == null)
                {
                    context.Response.StatusCode = 304;
                }
                else
                {

                }
            }
            else if (path == "~/auth/mnet/land.php" && method == "GET")
            {
                //this is called when Scarfy uses Moodle for authentication (using the above jump url)
                // eg http://www.scarfy.co.nz/auth/mnet/land.php?token=b4558516865861f0ac8b18f1a72e4c24552ca55a&idp=http://millie.id.co.nz/moodle&wantsurl=
                //token - used to send an XMLRPC call back to the moodle server
                //idp - the server to send the call back to
                //wantsurl - the url on Scarfy to go back to (as above)
                String Token = context.Request.Params["token"];
                String RemoteServer = context.Request.Params["idp"];
                String URL = context.Request.Params["wantsurl"];
            } else {
                //Don't know what to do with their request
                context.Response.StatusCode = 404;
            }
        }
    }
}
